//============================================================================
// Copyright (C) 2013 Brett R. Jones
//
// Issued to public domain 2013
//
// brettjones1900@gmail.com
// http://www.p2panarchy.com
//============================================================================
#include "VxDefs.h"

//============================================================================
//! blend 2 colors using alpha of src color to determine how much of src color is added to dest color
U32 VxBlendColors(	U32 u32DecalColor,	// color of upper layer ( decal or overlay )
					U32 u32DestColor )	// color of lower layer ( background )
{
	S32 s32SrcAlpha	= ( u32DecalColor & 0xff000000 ) >> 24;
	// temp for debug
	if( 255 == s32SrcAlpha )
	{
		// src is completely opaque.. so it is decal color
		return u32DecalColor;
	}
	else if( 0 == s32SrcAlpha )
	{
		// src is completely transparent.. so it is dest color
		return u32DestColor;
	}

	// get componet parts
	S32 s32SrcRed		= u32DecalColor & 0xff;
	S32 s32SrcGreen		= (u32DecalColor & 0xff00) >> 8;
	S32 s32SrcBlue		= (u32DecalColor & 0xff0000) >> 16;

	U32 u32DestAlpha	= (u32DestColor & 0xff000000) >> 24;
	S32 s32DestRed		= u32DestColor & 0xff;
	S32 s32DestGreen	= (u32DestColor & 0xff00) >> 8;
	S32 s32DestBlue		= (u32DestColor & 0xff0000) >> 16;
	
	// calculate resulting alpha
	U32 u32ResultAlpha = (s32SrcAlpha + u32DestAlpha);
	if( u32ResultAlpha > 255 )
	{
		u32ResultAlpha = 255;
	}

	// blend the colors using alpha channel
	S32 s32DeltaRed		= ( s32SrcRed - s32DestRed );
	S32 s32DeltaGreen	= ( s32SrcGreen - s32DestGreen );
	S32 s32DeltaBlue	= ( s32SrcBlue - s32DestBlue );

	U32 u32ResultRed = (U32)( s32DestRed + (( s32DeltaRed * s32SrcAlpha)/255));
	if( u32ResultRed > 255 )
	{
		u32ResultRed = 255;
	}
	U32 u32ResultGreen = (U32)( s32DestGreen + (( s32DeltaGreen * s32SrcAlpha)/255));
	if( u32ResultGreen > 255 )
	{
		u32ResultGreen = 255;
	}
	U32 u32ResultBlue = (U32)( s32DestBlue + (( s32DeltaBlue * s32SrcAlpha)/255));
	if( u32ResultBlue > 255 )
	{
		u32ResultBlue = 255;
	}
	return  (u32ResultAlpha<<24) | ( u32ResultBlue << 16 ) | (u32ResultGreen << 8) | u32ResultRed;
}
